package com.nercel.dsj.gksales.api.controller;

import com.alibaba.fastjson.JSON;
import com.nercel.dsj.gksales.exception.ResponseCode;
import com.nercel.dsj.gksales.exception.RestApiException;
import com.nercel.dsj.gksales.model.QueryParams;
import com.nercel.dsj.gksales.model.entity.Payment;
import com.nercel.dsj.gksales.model.entity.Permission;
import com.nercel.dsj.gksales.service.PaymentService;
import com.nercel.dsj.gksales.service.PermissionService;
import com.nercel.dsj.gksales.service.SellRecordService;
import com.nercel.dsj.gksales.thirdparty.alipay.config.AliPayConfig;
import com.nercel.dsj.gksales.util.SpringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author sunlin
 * @date 2018-11-19
 */
@RestController
@Api(tags = "TEST")
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TestApiController {

    private final PermissionService permissionService;

    private final PaymentService paymentService;

    private final SellRecordService sellRecordService;

	@GetMapping(value = "/api/v1/test2")
	@ApiOperation(value = "test")
	public void test2() {
		Payment payment = paymentService.findByOrderNumber("178fe7b1edb54bc981fc42be2ff61dd4");
				payment.setPayedTime(new Date());
				payment.setSuccessful(true);
				payment.setPayedNumber("test");
				paymentService.update(payment);
				sellRecordService.saveAndActivateWithPayment(payment);
	}

	@GetMapping(value = "/tencent1046218304465768959.txt")
	public void ssss(HttpServletResponse response) {
		try {
			response.getWriter().write("6805137568874160604");
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}


	@GetMapping(value = "/api/v1/test3")
	@ApiOperation(value = "test3")
	public void test32() {
		throw new RestApiException(ResponseCode.NOT_ENOUGH_AMOUNT);
	}


	@PostMapping(value = "/api/v1/test/mapping")
	@ApiOperation(value = "test")
	public void test(HttpServletRequest request, HttpServletResponse response) {
		List<String> requestMappings = getRequestMapping(request);
		List<Permission> permissions = permissionService.list(new QueryParams());
		SpringUtil.getRequestMapping(request);
		List<String> noPermissionRequestMappings =  getRequestListOfNotInPermissionList(permissions, requestMappings);
		System.out.println(JSON.toJSONString(noPermissionRequestMappings));
		System.out.println(requestMappings.size());
	}

	private List<String> getRequestListOfNotInPermissionList(List<Permission>permissions, List<String>requestMappings){
		List<String> result = new ArrayList<>();
		requestMappings.forEach(pattern ->{
			boolean inList = false;
			for(Permission permission : permissions){
				if(permission.getUrl().equals(pattern)){
					inList = true;
					break;
				}
			}
			if(!inList){
				result.add(pattern);
			}
		});
		return result;
	}


	public List<String> getRequestMapping(HttpServletRequest request) {
		List<String> uList = new ArrayList<>();//存储所有url集合
		WebApplicationContext wac = (WebApplicationContext) request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);//获取上下文对象
		Map<String, HandlerMapping> requestMappings = BeanFactoryUtils.beansOfTypeIncludingAncestors(wac, HandlerMapping.class, true, false);
		for(HandlerMapping handlerMapping : requestMappings.values()) {
			if(handlerMapping instanceof RequestMappingHandlerMapping) {
				RequestMappingHandlerMapping rmhm = (RequestMappingHandlerMapping) handlerMapping;
				Map<RequestMappingInfo, HandlerMethod> handlerMethods = rmhm.getHandlerMethods();
				for(RequestMappingInfo rmi : handlerMethods.keySet()) {
					//handlerMethods.get(rmi).getMethod().getDeclaredAnnotations()
					for(RequestMethod method : rmi.getMethodsCondition().getMethods()){
						PatternsRequestCondition prc = rmi.getPatternsCondition();
						Set<String> patterns = prc.getPatterns();
						for (String url : patterns){
							String pattern = method.name() + ":" + url;
							pattern = pattern.replaceAll("\\{.*?\\}","*");
							uList.add(pattern);
						}
					}
				}
			}
		}
		return uList;
	}
}
